from dg_cszg import models
from django.http import HttpResponse,JsonResponse
from django.db.models import Count, Min, Max, Sum,Q
import json
import math
import re



#提取数量值
def get_num(text):
    res=re.findall(re.compile(r'\d+'), str(text))
    return res[0] if len(res) else 0
#None过滤器
def pro_none(num):
    if num is None:
        return 0
    return num
#获取箱数件数
def getxj(in_list):
    x1 = in_list.filter(jldw='箱')
    x2 = in_list.filter(jldw=None, slz__icontains='箱')
    x = 0
    j = 0
    for i in x1:
        x += int(get_num(i.slz))
    for i in x2:
        x += int(get_num(i.slz[:-1]))
    j1 = in_list.filter(~Q(jldw='箱')).filter(~Q(jldw=None))
    j2 = in_list.filter(jldw=None).filter(~Q(slz__icontains='箱'))
    for i in j1:
        j += int(get_num(i.slz))
    for i in j2:
        j += int(get_num(i.slz))
    return x, j


#列出全部基金会
def jjh_list(request):
    records=models.jjh_info.objects.all()
    data=[]
    for record in records:
        data.append({"name": str(record.jjh), "income":str(record.zlr) +"万",
                     "outcome": str(record.zlc) +"万",
                     "time": str(record.rq)})
    result={"code":"200","ret_mes":"success","data":data}
    return HttpResponse(json.dumps(result))

#列出某基金会信息(目前就是总流入 总流出 发物统计 捐物统计.....)
def jjh_info(request):
    name=request.GET.get("name")
    records=models.jjh_info.objects.filter(jjh=name)
    if  records:
        records=records[0]
        data=json.loads(json.dumps(records, default=lambda obj: obj.__dict__))
        data["zlr"]=data["zlr"]+"万"
        data["zlc"] = data["zlc"] + "万"
    else:
        data=[]
    result={"code":"200","ret_msg":"success","data":data}
    return HttpResponse(json.dumps(result))



def grant_info(request):
    name = request.GET.get('name')
    offset=int(request.GET.get('offset'))
    limit=int(request.GET.get('limit'))
    size_records = models.grant_info.objects.filter(jjh=name).count()
    if size_records ==0:
        result = {"code": "100", "ret_msg": "fail","pages":0,"total":0,"data":[]}
        return HttpResponse(json.dumps(result))
    start=(offset-1)*limit
    end=limit if offset*limit <=size_records else size_records-start
    # end=(offset*limit) if (offset-1)*limit <=size_records else size_records
    sql_excute = "select * from dg_cszg_grant_info where jjh='" + name + "' limit " + str(start) + "," + str(end) + ";"
    grantlist = models.grant_info.objects.raw(sql_excute)
    result = {"code": "200", "ret_msg": "success","pages":math.ceil(size_records/limit),"total":size_records,"data": json.loads(json.dumps(list(grantlist), default=lambda obj: obj.__dict__))}
    return HttpResponse(json.dumps(result))


def donation_info(request):
    name = request.GET.get('name')
    offset=int(request.GET.get('offset'))
    limit=int(request.GET.get('limit'))
    size_records= models.donation_info.objects.filter(jjh=name).count()
    if size_records ==0:
        result = {"code": "100", "ret_msg": "fail","pages":0,"total":0,"data":[]}
        return HttpResponse(json.dumps(result))
    start=(offset-1)*limit
    # end=(offset*limit) if (offset-1)*limit <=size_records else size_records
    end=limit if offset*limit <=size_records else size_records-start
    sql_excute="select * from dg_cszg_donation_info where jjh='"+ name +"' limit "+str(start)+","+str(end)+";"
    # print(sql_excute)
    donationlist = models.donation_info.objects.raw(sql_excute)
    result = {"code": "200", "ret_msg": "success","pages":math.ceil(size_records/limit),"total":size_records,
              "data": json.loads(json.dumps(list(donationlist), default=lambda obj: obj.__dict__))}

    return HttpResponse(json.dumps(result))


def search_info(request):
    key = request.GET.get('key','')
    type = request.GET.get('type', '')
    if key=='' or type=='':
        return JsonResponse({'code':'200','ret_msg':'ERROR!params is none'})
    list = []
    count = 0
    if type=='d':
        list = models.donation_info.objects.filter(jzdw__contains=key)
    if type=='g':
        list = models.donation_info.objects.filter(ffdw__contains=key)
    count=len(list)
    res = {
        'code': '200',
        'ret_msg': 'success',
        'count':count,
        'data':json.loads(json.dumps(list(list), default=lambda obj: obj.__dict__))
    }
    return JsonResponse(res)
